import axios from 'axios';
var instance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 1000,
    withCredentials: false,
});

//添加一个请求拦截器
axios.interceptors.request.use(function(config) {
    console.log('before request');
    return config;
}, function(err) {
    return Promise.reject(err);
});

//添加一个响应拦截器
axios.interceptors.response.use(function(resp) {
    console.log('response before callback');
    let headers = resp['headers'];
    for (let h in headers) {
        console.log(h + ' -> ' + headers[h]);
    }
    return resp;
}, function(err) {
    return Promise.reject(err);
});

class Ajax {

    get(uri: string, param: Object, callback: Function) {
        axios
            .get(uri, param || {})
            .then(function(response) {
                console.log('cabllback');
                callback(response);
            })
            .catch(function(err) {
                Ajax.ajaxErrorHandler(err);
            });
    }

    post(uri: string, param: Object, callback: Function) {
        axios
            .post(uri, param || {})
            .then(function(response) {
                callback(response);
            })
            .catch(function(err) {
                Ajax.ajaxErrorHandler(err);
            });
    }

    getTemplate(uri: string, param: Object, callback: Function) {
        axios
            .request({
                url: uri,
                params: param || {},
                method: 'get',
                responseType: 'document'
            })
            .then(function(response) {
                callback(response);
            })
            .catch(function(err) {
                Ajax.ajaxErrorHandler(err);
            });
    }

    static ajaxErrorHandler(error: Object) {
        alert(error);
    }

}

const ajax = new Ajax();
export {
   ajax
}
